﻿//https://leetcode.cn/problems/combination-sum/?envType=study-plan-v2&envId=top-100-liked

class Solution {
    vector<vector<int>> ret;
    vector<int> path;
    int aim;
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target)
    {
        aim = target;
        dfs(candidates, 0, 0);
        return ret;
    }

    void dfs(vector<int>& candidates, int pos, int sum)
    {
        if (sum == aim)
        {
            ret.push_back(path);
            return;
        }

        if (sum > aim || pos == candidates.size())
            return;

        //可以选择多个
        for (int k = 0; k * candidates[pos] + sum <= aim; k++)
        {
            if (k)
                path.push_back(candidates[pos]);
            dfs(candidates, pos + 1, k * candidates[pos] + sum);
        }

        //恢复现场
        for (int k = 1; k * candidates[pos] + sum <= aim; k++)
        {
            path.pop_back();
        }
    }
};
